﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace IOA.MES.Client
{
    /// <summary>
    /// MissingSiteRecord.xaml 的交互逻辑
    /// </summary>
    public partial class MissingSiteRecord : Window
    {
        private int machineId = 0;
        private int pageIndex = 1;
        private int pageSize = 20;
        private int totalPage = 0;
        public MissingSiteRecord(int machineId)
        {
            InitializeComponent();
            this.machineId = machineId;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var startTime = DateTime.Today.AddDays(-2).AddHours(8);
            dpStratTime.SelectedDate = startTime;
            dpEndTime.SelectedDate = DateTime.Now;

            QueryRecords();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            pageIndex = 1;
            var btnName = (sender as Button).Name;
            if (string.Equals(btnName, "btnSearch", StringComparison.CurrentCultureIgnoreCase))
            {
                QueryRecords();
            }
            else if (string.Equals(btnName, "btnExport", StringComparison.CurrentCultureIgnoreCase))
            {
                QueryRecords(true);
            }
        }

        private void btnPage_Click(object sender, RoutedEventArgs e)
        {
            var btnName = (sender as Button).Name;
            if (string.Equals(btnName, "btnPrePage", StringComparison.CurrentCultureIgnoreCase))
            {
                if (pageIndex > 1)
                {
                    pageIndex--;
                    QueryRecords();
                }
            }
            else if (string.Equals(btnName, "btnNextPage", StringComparison.CurrentCultureIgnoreCase))
            {
                if (pageIndex < totalPage)
                {
                    pageIndex++;
                    QueryRecords();
                }
            }
        }

        private void QueryRecords(bool export = false)
        {
            var response = BaseEnv.InvokeApi<QueryMissingViaSiteRecordsResponse>("/api/Machine/QueryMissingViaSiteRecords", new
            {
                PageIndex = pageIndex,
                PageSize = export ? 0 : pageSize,
                SiteType = BaseEnv.MachineType,
                MachineId = machineId,
                StartTime = dpStratTime.SelectedDate.Value,
                EndTime = dpEndTime.SelectedDate.Value
            });
            if (response.ErrCode != 200)
            {
                CommonMessage.Alert(this, response.ErrMsg);
                return;
            }
            response.Data.Components.ForEach(_ =>
            {
                _.No = (pageIndex - 1) * pageSize + response.Data.Components.IndexOf(_) + 1;
            });

            if (!export)
            {
                dgRecord.ItemsSource = null;
                dgRecord.ItemsSource = response.Data.Components;

                totalPage = response.TotalCount % pageSize == 0 ? response.TotalCount / pageSize : (response.TotalCount / pageSize + 1);
                lblPage.Content = $"{pageIndex}/{totalPage}";
            }
            else
            {
                var book = new XSSFWorkbook();
                var sheet = book.CreateSheet();
                for (int i = 0; i <= 5; i++)
                {
                    sheet.SetColumnWidth(i, 8 * 400 + 200);
                }
                var styleCenter = book.CreateCellStyle();
                styleCenter.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                styleCenter.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                styleCenter.BorderBottom = BorderStyle.Thin;
                styleCenter.BorderLeft = BorderStyle.Thin;
                styleCenter.BorderRight = BorderStyle.Thin;
                styleCenter.BorderTop = BorderStyle.Thin;

                var rowHeader = sheet.CreateRow(0);
                rowHeader.Height = 30 * 20;
                rowHeader.CreateCell(0).SetCellValue("序号");
                rowHeader.CreateCell(1).SetCellValue("组件条码");
                rowHeader.CreateCell(2).SetCellValue("分片时间");
                rowHeader.CreateCell(3).SetCellValue("工单号");
                rowHeader.CreateCell(4).SetCellValue("订单号");

                foreach (var item in response.Data.Components)
                {
                    var tmpRow = sheet.CreateRow(1 + response.Data.Components.IndexOf(item));
                    tmpRow.Height = 30 * 20;
                    tmpRow.CreateCell(0).SetCellValue(item.No);
                    tmpRow.CreateCell(1).SetCellValue(item.BarCode);
                    tmpRow.CreateCell(2).SetCellValue(item.DistributeTime.ToString("yyyy/MM/dd HH:mm:ss"));
                    tmpRow.CreateCell(3).SetCellValue(item.WorkOrderNo);
                    tmpRow.CreateCell(4).SetCellValue(item.OrderNo);
                }

                var filePath = $"{Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}\\{DateTime.Now:yyyyMMddHHmmss}_漏扫导出.xlsx";
                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    book.Write(fs);
                }
                book = null;

                System.Diagnostics.Process.Start(filePath);
            }
        }
    }
}
